package grg.app.beeper

import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.util.SparseArray
import androidx.annotation.RawRes


/**
 *
 * 声音工具
 *
 */
object BeeperHelper {
    var enable = true
    private var soundId = SparseArray<Int>()
    var mSoundPool: SoundPool? = null

    /**
     * 初始化
     *
     * @param context Context
     */
    inline fun init(
        soundPoolBuilderBlock: SoundPool.Builder.() -> Unit = {}
    ) {
        // 第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSoundPool = SoundPool.Builder()
                .setAudioAttributes(
                    AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .build()
                )
                .setMaxStreams(8)
                .apply(soundPoolBuilderBlock)
                .build()
        } else {
            mSoundPool = SoundPool(1, AudioManager.STREAM_ALARM, 1)
        }
    }

    /**
     * 发声
     *
     * @param soundRaw
     */
    fun beep(@RawRes soundRaw: Int) {
        if (!enable) {
            return
        }
        if (mSoundPool == null) {
            return
        }
        val targetId = soundId[soundRaw] ?: return
        mSoundPool!!.play(targetId, 1f, 1f, 0, 0, 1f)
    }

    /**
     * 释放资源
     */
    fun release() {
        if (mSoundPool != null) {
            mSoundPool!!.release()
            mSoundPool = null
        }
    }
}